<template>
  <page-header-wrapper :title="false">
    <a-card title="业务管理">
      <template slot="extra">
        <a-button size="small" icon="redo" type="primary" @click="resetForm">刷新</a-button>
      </template>
      <div class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          ref="queryParam"
          :model="queryParam"
        >
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="业务名称">
                <a-input v-model="queryParam['filter[business_name]']" placeholder="请输入业务名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="合同编号">
                <a-input v-model="queryParam['filter[contract_no]']" placeholder="请输入合同编号"/>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="业务编号">
                  <a-input v-model="queryParam['filter[business_no]']" placeholder="请输入业务编号"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="下单时间">
                  <a-range-picker v-model="submitTime" @change="onChangeSubmit" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="领取时间">
                  <a-range-picker v-model="receiveTime" @change="onChangeReceive" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所属顾问">
                  <a-select
                    show-search
                    v-model="queryParam['filter[adviser_uid]']"
                    placeholder="输入要搜索的顾问姓名"
                    :default-active-first-option="false"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    @search="onSearch"
                  >
                    <a-select-option v-for="(item,index) in searchSource" :key="index" :value="index">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="流程状态">
                  <a-select v-model="queryParam['filter[status2]']" placeholder="请选择流程状态">
                    <a-select-option v-for="(item,index) in statusOpts" :key="index" :value="index">{{item}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col v-if="group == 'small_leader'" :md="6" :sm="24">
                <a-form-model-item label="专利流程">
                  <a-select v-model="queryParam['filter[receive_uid]']" placeholder="请选择专利流程">
                    <a-select-option v-for="(item,index) in processOpts" :key="index" :value="index">{{item}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="专利老师">
                  <a-select v-model="queryParam['filter[patenteer]']" placeholder="请选择专利老师">
                    <a-select-option v-for="(item,index) in patentOpts" :key="index" :value="index">{{item}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="专利材料">
                  <a-select v-model="queryParam['filter[is_patenteer_file]']" placeholder="专利师是否上传材料">
                    <a-select-option :value="1">已上传</a-select-option>
                    <a-select-option :value="2">未上传</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class='table-page-search-submitButtons' :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" @click="$refs.table.refresh(true)">搜索</a-button>
                  <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
                </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div>
        <s-table
          bordered
          size="middle"
          ref="table"
          :row-class-name="(record) => { if (record.status2_code == 20) return 'table-color-dust' }"
          :row-key="(record) => record.cb_id"
          :columns="businessColumns"
          :data="businessData"
        >
          <div
            slot="filterDropdown"
            slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
            style="padding: 8px"
          >
            <a-input
              v-ant-ref="c => (searchInput = c)"
              :placeholder="`搜索${column.title}`"
              :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block;"
              @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
              @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
              type="primary"
              icon="search"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              搜索
            </a-button>
            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
              重置
            </a-button>
          </div>
          <template slot="contract_no" slot-scope="text,record">
            {{text}}<br>
            {{record.business_no}}
          </template>
          <template slot="adviser" slot-scope="text,record">
            <a-tag>{{text}}</a-tag><br>
            <a-tag>{{record.group_type}}组</a-tag><br>
            <a-tag>{{record.leader}}</a-tag>
          </template>
          <template slot="zl_name" slot-scope="text, record">
            <a @click="onEdit(record.cb_id)"><a-icon type="edit" v-if="text"/> {{text}}</a>
          </template>
          <template slot="submit_mats_time" slot-scope="text,record">
            {{text}}<br>
            {{record.received_at}}
          </template>
          <template slot="receiver" slot-scope="text,record">
            <a-select
              v-if="group == 'small_leader'"
              style="width: 110px"
              size="small"
              v-model="receiverForm['receiver' + record.cb_id]"
              @change="value => onChangeReceiver(value, record.cb_id)"
              :loading="receiverLoading"
            >
              <a-select-option v-for="(item,index) in appointOpts" :key="index" :value="index">{{item}}</a-select-option>
            </a-select>
            <a-tag v-else>{{appointOpts[text]}}</a-tag>
          </template>
          <template slot="history" slot-scope="text,record">
            <a @click="historyModal(record.cb_id)">{{text}}</a>
          </template>
          <template slot="submit_mats_time" slot-scope="text, record">
            {{text}}<br>
            {{record.received_at}}
          </template>
          <template slot="status2" slot-scope="text,record">
            <a-button v-if="record.status2_code == 22 || record.status2_code == 20 || record.status2_code == 35" size="small" icon="edit" type="danger" @click="changeStatus(record.cb_id)">{{text}}</a-button>
            <a-button
              ghost
              v-if="record.status2_code == 40 || record.status2_code == 30"
              type="danger"
              size="small"
              @click="changeStatus(record.cb_id)"
            >
              {{text}}
            </a-button>
            <a-button
              ghost
              v-if="record.status2_code == 24 || record.status2_code == 32 || record.status2_code == 36"
              type="primary"
              size="small"
              @click="changeStatus(record.cb_id)"
            >
              {{text}}
            </a-button>
            <a-button
              ghost
              v-if="record.status2_code == 34"
              type="primary"
              size="small"
              @click="changeStatus(record.cb_id)"
            >
              {{text}}
            </a-button>
          </template>
          <template slot="patenteer_filename" slot-scope="text,record">
            <a-button v-if="text != ''" type="link" icon="download" size="small" @click="download(text, record.patenteer_file)"><ellipsis :length="10">{{text}}</ellipsis></a-button>
            <a-tag v-else color="red">暂无材料</a-tag>
          </template>
          <template slot="patenteer" slot-scope="text,record">
            <a-select
              v-if="text == '' && group == 'small_leader'"
              style="width:110px"
              placeholder="请指定专利师"
              size="small"
              v-model="patentForm['appoint' + record.cb_id]"
              @change="value => onChangePatenteer(value, record.cb_id)"
              :loading="patentLoading"
            >
              <a-select-option v-for="(item,index) in appointEngOpts" :key="index" :value="index">{{item}}</a-select-option>
            </a-select>
            <a-select
              v-else-if="text != '' && group == 'small_leader'"
              style="width:110px"
              size="small"
              placeholder="请指定专利师"
              v-model="patentForm['patenteer' + record.cb_id]"
              @change="value => onChangePatenteer(value, record.cb_id)"
              :loading="patentLoading"
            >
              <a-select-option v-for="(item,index) in appointEngOpts" :key="index" :value="index">{{item}}</a-select-option>
            </a-select>
            <div v-else-if="group != 'small_leader'">{{appointEngOpts[text]}}</div>
          </template>
<!--          <template slot="official_fee" slot-scope="text,record">-->
<!--            <a-tag color="red">官费：{{text}}</a-tag><br>-->
<!--            <a-tag color="red">价格：{{record.price}}</a-tag><br>-->
<!--            <a-tag color="red">代理费：{{record.agency_fee}}</a-tag>-->
<!--          </template>-->
          <template slot="djs" slot-scope="text,record">
            <a-statistic-countdown v-if="record.status2_code == 20" :value="record.received_time_stamp * 1000 + 1000 * 60 * 60 * 24 * 3" format="D天H时m分s秒" />
            <a-tag v-else>无需计时</a-tag>
          </template>
          <template slot="additional_content" slot-scope="text,record">
            <a-button :disabled="record.exts.length === 0" type="link" @click="onExtView(record.exts)">查看</a-button>
          </template>
          <template slot="action" slot-scope="text,record">
            <a-dropdown-button size="small" type="primary" @click="handleButtonClick(record.cb_id)">
              查看
              <a-menu slot="overlay" @click="(e) => handleMenuClick(e, record.cb_id)">
                <a-menu-item key="1"> <a-icon type="download" />下载</a-menu-item>
                <a-menu-item key="2"> <a-icon type="upload" />上传</a-menu-item>
                <a-menu-item key="3"> <a-icon type="setting" />设置</a-menu-item>
              </a-menu>
            </a-dropdown-button>
          </template>
        </s-table>
      </div>
    </a-card>
    <a-modal
      centered
      title="上传材料"
      :confirm-loading="loading"
      v-model="uploadVisible"
      @ok="submitUpload"
    >
      <a-form-model
        :model="uploadForm"
      >
        <a-form-model-item label="业务名称">
          <a-input disabled v-model="uploadForm.business_name" type="text" />
        </a-form-model-item>
        <a-form-model-item label="整理后材料">
          <a-upload
            name="file"
            :multiple="true"
            :headers="headers"
            :action="uploadUrl"
            :show-upload-list="false"
            @change="onChange"
          >
            <a-button type="danger"> <a-icon type="upload" />上传整理后的材料</a-button>
          </a-upload>
        </a-form-model-item>
        <a-button v-if="uploadForm.mat" size="small" type="link" icon="download" @click="download(uploadForm.mat.file)"><ellipsis :length="30">{{uploadForm.mat.filename}}</ellipsis></a-button>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      title="下载材料"
      v-model="downloadVisible"
    >
      <a-alert>
        <template slot="message">
          <b>整理后的材料：</b><a :href="zip.mat_file">{{zip.mat_filename}}</a>
        </template>
      </a-alert>
      <a-divider />
      <a-form-model
        ref="downloadForm"
      >
        <a-form-model-item v-for="(item,index) in downloadForm" :key="index">
          <template slot="label"><b>{{item.mat_name}}</b></template>
          <div v-if="item.type == 'image'"><img style="width: 100%" :src="item.value"/></div>
          <div v-if="item.type == 'file'">
            <div v-if="item.value != ''">
              <a-button size="small" type="link" icon="download" @click="download(item.filename, item.value)">{{item.filename}}</a-button>
            </div>
            <div v-else>无</div>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      v-model="historyVisible"
      title="历史信息"
      :footer="null"
    >
      <a-timeline>
        <a-timeline-item v-for="(item,index) in historyData" :key="index">
          {{item.step}}{{item.username}},{{item.notes}} {{item.created_at}}
        </a-timeline-item>
      </a-timeline>
    </a-modal>
    <a-modal
      centered
      v-model="submitVisible"
      title="编辑状态"
      @ok="submitChangeStatus"
      @cancel="onCancel"
    >
      <a-form-model
        ref="ruleForm"
        :model="changeStatusForm"
      >
        <a-form-model-item prop="status2">
          <a-radio-group v-model="changeStatusForm.status2" @change="onChangeStatus">
            <a-radio :disabled="index == 34" v-for="(item, index) in changeStatusOpts" :key="index" :value="index">
              {{item}}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item prop="notes">
          <a-textarea :rows="4" v-model="changeStatusForm.notes" placeholder="请输入材料备注"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      title="修改专利名称"
      v-model="visible3"
      @ok="submitName"
    >
      <a-form-model>
<!--        <a-form-model-item label="原专利名">-->
<!--          <a-input disabled type="text" value="机械" />-->
<!--        </a-form-model-item>-->
        <a-form-model-item label="专利名称">
          <a-input v-model="zlname" type="text" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="设置案件类型"
      v-model="visible4"
      :width="400"
      @ok="onSubmit"
    >
      <a-form-model
        ref="typeForm"
        :model="typeForm"
        :destory-on-close="true"
      >
        <a-form-model-item>
          <a-select v-model="defaultLabel">
            <a-select-option v-for="(item,index) in typeOpts" :key="index" :value="index">{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <ext-view v-if="extVisible" :ext-list="extList" @cancel="onCancelExt"></ext-view>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import storage from 'store'
import { ACCESS_TOKEN, GROUP, ROLE } from '@/store/mutation-types'
import apis from '@/api'
import businessColumns from '@/columns/patent.process'
import {
  getArrangeList,
  getHistoryList,
  getArrangeEditStatus,
  postArrangeEditStatus,
  appointPatent,
  getArrangeDownload,
  getArrangeUpload,
  onCompletionAdviser,
  postArrangeUpload,
  postFlow, getEditLabel, postEditLabel, postUpdateName, getUpdateName
} from '@/api/patent.process'
import ExtView from '@/views/patent-process/components/ExtView'

export default {
  components: {
    ExtView,
    Ellipsis,
    STable
  },
  name: 'BusinessList',
  data () {
    return {
      queryParam: {},
      advanced: true,
      tab: '1',
      businessColumns: businessColumns.business,
      businessData: parameters => {
        return getArrangeList(Object.assign(parameters, this.queryParam)).then(res => {
          this.patentForm = {}
          this.statusOpts = res.result.status2_opts
          this.patentOpts = res.result.engineer
          this.processOpts = res.result.flow
          this.appointOpts = res.result.flow_appoint
          this.appointEngOpts = res.result.engineer_appoint
          for (let i = 0; i < res.result.data.length; i++) {
            this.patentForm['patenteer' + res.result.data[i].cb_id] = res.result.data[i].patenteer
            this.receiverForm['receiver' + res.result.data[i].cb_id] = res.result.data[i].receiver
          }
          return res.result
        })
      },
      zlid: '',
      zlname: '',
      adviserOpts: {},
      patentOpts: {},
      statusOpts: {},
      appointOpts: {},
      processOpts: {},
      appointEngOpts: {},
      changeStatusOpts: {},
      changeStatusForm: {},
      uploadVisible: false,
      downloadVisible: false,
      submitVisible: false,
      historyVisible: false,
      uploadForm: {},
      downloadForm: {},
      historyData: [],
      patentForm: {},
      receiverForm: {},
      searchSource: [],
      patentLoading: false,
      receiverLoading: false,
      zip: {},
      uploadUrl: apis.Upload,
      headers: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      group: storage.get(GROUP),
      groupType: storage.get(ROLE),
      loading: false,
      submitTime: [],
      receiveTime: [],
      processForm: {},
      visible3: false,
      visible4: false,
      typeForm: {},
      defaultLabel: '',
      typeOpts: [],
      extVisible: false,
      extList: []
    }
  },
  methods: {
    onChangeSubmit (date, dateString) {
      this.queryParam['filter[submit_mats_time_start]'] = dateString[0]
      this.queryParam['filter[submit_mats_time_end]'] = dateString[1]
    },
    onChangeReceive (date, dateString) {
      this.queryParam['filter[received_at_start]'] = dateString[0]
      this.queryParam['filter[received_at_end]'] = dateString[1]
    },
    historyModal (id) {
      const app = this
      getHistoryList(id).then(res => {
        if (res.status === 0) {
          app.historyData = res.result.data
          app.historyVisible = true
        } else {
          app.$error({
            title: '警告',
            content: res.msg
          })
        }
      })
    },
    changeStatus (id) {
      const app = this
      app.changeStatusForm = {}
      app.changeStatusForm['cb_id'] = id
      getArrangeEditStatus(id).then(res => {
        if (res.status === 0) {
          app.changeStatusOpts = res.result.status2_items
          app.changeStatusForm.notes = res.result.contract_business.notes
          app.submitVisible = true
        } else {
         app.$warning({
           title: res.msg
         })
          return false
        }
      })
    },
    submitChangeStatus () {
      const app = this
      const data = {}
      data['contract_business[status2]'] = app.changeStatusForm.status2
      data['contract_business[notes]'] = app.changeStatusForm.notes
      postArrangeEditStatus(app.changeStatusForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          app.onCancel()
          app.$refs.table.refresh()
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetForm () {
      this.queryParam = {}
      this.submitTime = []
      this.receiveTime = []
      this.$refs.table.refresh(true)
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },
    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    onCancel () {
      this.changeStatusForm = {}
      this.submitVisible = false
    },
    onChangePatenteer (value, id) {
      const app = this
      const data = {}
      app.patentLoading = true
      data['patenteer'] = value
      app.$confirm({
        title: '是否确认指定专利师',
        onOk: () => {
          appointPatent(id, data).then(res => {
            if (res.status === 0) {
              app.patentLoading = false
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
              app.patentForm['appiont' + id] = {}
              app.patentLoading = false
              app.$refs.table.refresh()
            }
          })
        },
        onCancel: () => {
          app.patentForm['appiont' + id] = {}
          app.patentLoading = false
          app.$refs.table.refresh()
        }
      })
    },
    onChangeReceiver (value, id) {
      const app = this
      const data = {}
      app.receiverLoading = true
      data['flow'] = value
      app.$confirm({
        title: '更改流程人员',
        onOk: () => {
          postFlow(id, data).then(res => {
            if (res.status === 0) {
              app.receiverLoading = false
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
              app.receiverForm['receiver' + id] = {}
              app.receiverLoading = false
              app.$refs.table.refresh()
            }
          })
        },
        onCancel: () => {
          app.receiverForm['receiver' + id] = {}
          app.receiverLoading = false
          app.$refs.table.refresh()
        }
      })
    },
    onSearch (searchText) {
      onCompletionAdviser(searchText).then(res => {
        this.searchSource = res.result.data
      })
    },
    onDownload (id) {
      getArrangeDownload(id).then(res => {
        this.downloadForm = res.result.data
        this.zip['mat'] = res.result.mat
        this.zip['mat_filename'] = res.result.mat_filename
        this.downloadVisible = true
      })
    },
    onUpload (id) {
      const app = this
      getArrangeUpload(id).then(res => {
        if (res.status === 0) {
          app.uploadForm = res.result
          app.uploadForm['cb_id'] = id
          app.uploadVisible = true
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    onChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return false
      }
      if (info.file.status === 'done') {
        this.uploadForm.mat.filename = info.file.name
        this.uploadForm.mat.file = info.file.response.result.url
        this.loading = false
      }
    },
    submitUpload () {
      const app = this
      const data = {}
      data['mat[file]'] = app.uploadForm.mat.file
      data['mat[filename]'] = app.uploadForm.mat.filename
      postArrangeUpload(app.uploadForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          app.uploadVisible = false
          app.$refs.table.refresh()
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    handleButtonClick (id) {
      if (this.groupType === 'proced_zl_engineer') {
        this.$router.push({ name: 'BusinessEdit', params: { id } })
      } else {
        this.$router.push({ name: 'AdminDetail', params: { id } })
      }
    },
    handleMenuClick (e, id) {
      if (e.key === '1') {
        this.onDownload(id)
      } else if (e.key === '2') {
        this.onUpload(id)
      } else if (e.key === '3') {
        getEditLabel(id).then(res => {
          this.typeForm = {}
          this.typeForm['id'] = id
          this.typeOpts = res.result.labelOpts
          this.defaultLabel = (res.result.contractBusinessLabel).toString()
          this.visible4 = true
        })
      }
    },
    onChangeStatus (e) {
      this.changeStatusForm.status2 = e.target.value
    },
    download (name, url) {
      const downloadUrl = apis.Download
      const params = '?filename=' + name + '&value=' + url
      window.open(downloadUrl + params)
    },
    onAppointFlow () {
      const app = this
      postFlow(this.processForm.cb_id, this.processForm).then(res => {
        if (res.status === 0) {
          app.processVisible = false
          app.$refs.table.refresh()
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    onEdit (id) {
      getUpdateName(id).then(res => {
        if (res.status === 0) {
          this.zlname = res.result.zl_name
          this.zlid = id
          this.visible3 = true
        } else {
          this.$error({
            title: '警告',
            content: res.msg
          })
        }
      })
    },
    onSubmit () {
      const app = this
      const data = {}
      data['patentLabel'] = app.defaultLabel
      postEditLabel(this.typeForm.id, data).then(res => {
        app.visible4 = false
        app.$refs.table.refresh()
      })
    },
    submitName () {
      const app = this
      const data = {}
      data['name'] = app.zlname
      postUpdateName(app.zlid, data).then(res => {
        if (res.status === 0) {
          app.$refs.table.refresh()
          app.visible3 = false
        } else {
          app.$error({
            title: '警告',
            content: res.msg
          })
        }
      })
    },
    onExtView (ext) {
      this.extList = ext
      this.extVisible = true
    },
    onCancelExt (visible) {
      this.extVisible = visible
    }
  }
}
</script>

<style scoped>
  /deep/ .ant-statistic-content {
    font-size: 16px;
    color: #f00;
  }
  /deep/ .ant-table-tbody > tr.table-color-dust {
    background-color: #ffcccc;
  }
</style>
